package com.fkcai.hansoul.common.util;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import static ch.qos.logback.core.joran.util.beans.BeanUtil.toLowerCamelCase;

/**
 * 转换工具类
 */
public class ConverterUtil {
	/**
	 *  将对象转换为 Map
	 * @param obj 对象
	 * @return  Map
	 */
	public static Map<String, Object> convertToMap(Object obj) {
		HashMap<String, Object> map = new HashMap<>();
		
		if (obj == null) return map;
		
		Class<?> aClass = obj.getClass();
		Method[] methods = aClass.getDeclaredMethods();
		
		for (Method method : methods) {
			// 匹配getter方法
			if (method.getName().startsWith("get") && !method.getName().equals("getClass")) {
				String key = toLowerCamelCase(method.getName().substring(3)); // 去掉get并转首字母小写
				try {
					Object value = method.invoke(obj);
					map.put(key, value);
				} catch (Exception e) {
					Result.fail(ResultCode.FILE_FORMAT_ERROR);
				}
			}
		}
		
		return map;
	}
}
